<template>
    <div class="container">
      <div class="containerEart">
        <p class="dialogTitle">需紧急安置人员</p>
        <div class="header">
          <span class="title">震情趋势：</span>
          <div class="icon">
              <svg-icon class-name="error-icon" icon-class="error" style="margin-right:10px" v-if="showIcon"/><span>{{titleOption}}</span>
          </div>
        </div>
      </div>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAssess">
            <svg-icon class-name="assess-icon" icon-class="assess" /><span style="margin-left:10px">评估</span>
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="openUpload">
            <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">成果上传</span>
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleDownload">
            <svg-icon class-name="download-icon" icon-class="download" /><span style="margin-left:10px">下载</span>
          </el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="primary" @click="handleSubmit">
            <svg-icon class-name="submit-icon" icon-class="submit" /><span style="margin-left:10px">提交</span>
          </el-button>
        </el-col> -->
      </el-row>
  
      <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="评估内容" align="center" prop="udContent" />
        <el-table-column label="生成时间" align="center" prop="udDate" />
        <el-table-column label="业务人员" align="center" prop="udPeople" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" @click="handleDetil(scope.row)">查看</el-button>
            <el-button type="text" @click="handledel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 上传对话框 -->
      <el-dialog v-model="open" width="800px" :title="title">
        <p></p>
        <el-form ref="uploadUdRef" :model="queryParams" :rules="rules" label-width="150px">
            <el-form-item label="上传图片" prop="pictureId">
              <image-upload ref="imageUpload" :limit="limit" :disabled="isViewFile" v-model="queryParams.attach" />
            </el-form-item>
            <el-form-item label="图片标题" prop="pictureTitle">
              <el-input v-model="queryParams.pictureTitle" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="上传附件" prop="udFileId">
                <file-upload ref="udFileRef" :limit="limit" :fileType="['xlsx']" v-model="queryParams.attachment" @uploadFile="uploadFile" @delFile="delFile" />
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('需紧急安置人员模板.xlsx')">下载模板</el-link>
                  <!-- <p style="color:#409eff;cursor: pointer;" @click="handleDown('需紧急安置人员模板.xlsx')">模板下载</p> -->
                  <div style="width:100%">
                <el-button type="primary" :disabled="disabledUdFile" @click="createExcle">生成表格</el-button>
                <el-table v-loading="loading1" :data="tableList" stripe v-if="showExcle" style="margin:20px 0">
                <template v-for="(item,index) in tableTitle" :key="index">
                  <el-table-column :label="item.label" align="center" :prop="item.prop" />
                </template>
              </el-table>
              </div>
            </el-form-item>
            <el-form-item label="附件标题" prop="udTitle">
              <el-input v-model="queryParams.udTitle" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="描述" prop="udDescription">
              <el-input v-model="queryParams.udDescription" type="textarea" maxlength="300" show-word-limit
                :autosize="{ minRows: 3, maxRows: 5}" placeholder="请输入描述" />
            </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleUpload">确定</el-button>
            <el-button @click="cancelUpload">取消</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 商会对话框 -->
      <el-dialog v-model="showOption" width="400px" title="震情趋势" :close-on-click-modal="false">
        <p class="worrning">震情趋势已发生变化，请注意！</p>
        <el-radio v-model="radioOption" label="true" style="margin-left:10px">今日不再提醒</el-radio>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" :disabled="!radioOption" @click="ok">确定</el-button>
            <el-button @click="cancelOption">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  <script setup name="urgency">
  import { listUrgency, getUrgency, uploadUrgency, updateUrgency, delUrgency ,createUrgencyExcle, downTemplate } from "@/api/assess/urgency";
  import { setcookieTimeFun, getCookieFun } from "@/utils/popout"
  
  const { proxy } = getCurrentInstance();
  const route = useRoute();
  const showIcon = ref(false);
  const titleOption = ref();
  const loading = ref(false);
  const loading1 = ref(false);
  const showOption = ref(false);
  const open = ref(false);
  const radioOption = ref(false);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const title = ref("");
  const id = ref();
  const limit = ref(1)
  const isViewFile = ref(false);
  const udRelation = ref();
  const disabledUdFile = ref(true);
  const showExcle = ref(false); 
  const tableList = ref([]);
  const tableTitle = ref([]);
  const data = reactive({
    queryParams: {
      pictureId:'',
      attach:[],
      pictureTitle:'',
      udContent:'需紧急安置人员表格',
      udFileId: '',
      attachment: [],
      udTitle: '',
      udDescription: '',
    },
    dataList: [],
    rules: {
      udFileId: [{ required: true, message: "附件不能为空", trigger: "blur" }],
      udTitle: [{ required: true, message: "标题不能为空", trigger: "blur" }],
      udDescription: [{ required: true, message: "描述不能为空", trigger: "blur" }],
    }
  })
  const { queryParams, dataList, rules } = toRefs(data)
  
  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.udId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  /** 获取列表操作 */
  function getList() {
    udRelation.value = route.query.id
    id.value = route.query.id;
    // id.value = '123';
    // udRelation.value = '123';
    loading.value = true;
    listUrgency(id.value).then((response) => {
      dataList.value = response.data.lists;
      titleOption.value = response.data.utOpinion;
      console.log(titleOption.value);
      showIcon.value = Boolean(Number(response.data.ktOpinionStatus));
      loading.value = false;
    });
  }
  // 打开成果上传开关
  function openUpload() {
    reset();
    isViewFile.value = false;
    title.value = "上传"
    open.value = true;
  }
  
  // 重置上传
  function reset() {
    queryParams.value = {
      pictureId:'',
      attach:[],
      pictureTitle:'',
      udContent:'需紧急安置人员表格',
      udFileId: '',
      attachment: [],
      udTitle: '',
      udDescription: '',
    }
    proxy.resetForm("uploadUdRef");
    disabledUdFile.value = true;
    showExcle.value = false;
    tableTitle.value = [];
    tableList.value = [];
  }
  
  // 成果上传
  function handleUpload() {
    console.log(s["imageUpload"].fileList)
  const fileList = JSON.parse(JSON.stringify(proxy.$refs["imageUpload"].fileList));
  const attachIds = [];
  for (var i = 0; i < fileList.length; i++) {
    attachIds.push(fileList[i].attachId)
  }
  queryParams.value.pictureId = attachIds.join(",");
    proxy.$refs["uploadUdRef"].validate(valid => {
      if (valid) {
        if(tableTitle.value.length==0){
          proxy.$modal.msgWarning("表格未生成");
        }else{
          if (title.value == '上传') {
            console.log(dataList.value.length == 0);
          let flag = false;
          if (dataList.value.length == 0) {
            flag = false;
          } else {
            // 查看是否重复
            flag = true
          }
          flag ? updateUpload() : upload();
        } else if (title.value == '查看') {
          updateUrgency(queryParams.value).then(response => {
            proxy.$modal.msgSuccess("保存成功");
            open.value = false;
            getList();
          });
        }
        }

      }
    });
  }
  function upload() {
    console.log('上传');
    uploadUrgency({ ...queryParams.value, udRelation: udRelation.value }).then(response => {
      proxy.$modal.msgSuccess("上传成功");
      open.value = false;
      getList();
    }).catch(() => { });
  }
  // 是否覆盖
  function updateUpload() {
    proxy.$modal.confirm('是否确认覆盖需紧急安置人员内容为"' +queryParams.value.udContent + '"的数据项？').then(function () {
      return uploadUrgency({ ...queryParams.value, udRelation: udRelation.value });
    }).then(() => {
      proxy.$modal.msgSuccess("上传成功");
      open.value = false;
      getList();
    }).catch(() => { });
  }
  
  function getDetail(id) {
    getUrgency(id).then(response => {
      queryParams.value = response.data.urgencysettleData;
      queryParams.value.attachment = [response.data.attach];
       queryParams.value.attach =response.data.imageObj? [response.data.imageObj]:[];
      Object.entries(response.data.forms[0]).forEach(item=>{
      tableTitle.value.push({label:item[1],prop:item[0]})
      })
      tableList.value = response.data.forms.splice('1') ;
      disabledUdFile.value = false;
      showExcle.value = true;
      title.value = "查看"
      open.value = true;
    })
  }
  
  /** 查看方法*/
  function handleDetil(row) {
    title.value = '查看';
    reset();
    getDetail(row.udId)
  }
  
  // 取消成果上传
  function cancelUpload() {
    reset();
    open.value = false;
  }
  
  /** 删除按钮操作 */
  function handledel(row) {
    const id = row.udId;
    proxy.$modal.confirm('是否确认删除' + row.udContent + '的数据项？').then(function () {
      return delUrgency(id);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  }

  // 删除成功
  function delFile(val){
    queryParams.value.udFileId = val;
    disabledUdFile.value = true;
    showExcle.value = false;
  }

// 上传成功
  function uploadFile(val){
    queryParams.value.udFileId = val;
    disabledUdFile.value = false;
  }

// 生成表格
function createExcle(){
  loading1.value = true;
  createUrgencyExcle({udFileId:queryParams.value.udFileId}).then(res=>{
    showExcle.value = true;
    tableTitle.value=[];
    Object.entries(res.data[0]).forEach(item=>{
      tableTitle.value.push({label:item[1],prop:item[0]})
    })
    tableList.value = res.data.splice('1') ;
    loading1.value = false;
  })
}

// 模板下载
function importTemplate(name) {
  proxy.download("/fxfzaqbz/data/downloadExcel", {
    fileName:name
  }, name);
};
  
  // 评估
  function handleAssess() {
  
  }
  
  // 下载
  function handleDownload() {
  
  }
  
  // 提交
  function handleSubmit() {
  
  }
  
  // 监听单选按钮
  watch(showIcon, (val) => {
    console.log(val);
    showOption.value = val;
    if(showOption.value){
      getTimeSetCookieFun(`urgencyCookie${route.query.id}`)
    }
  })
  
  // 获取日期时间
  function getTimeSetCookieFun(name) {
    var day = getCookieFun(name) == '' ? '' : getCookieFun(name);
    console.log(day,'获取cookie');
    if (day == '') {
      // console.log('没有cookie,说明过期或者还没有存')
      showOption.value = true;
    } else {
      var newTime = new Date().getDate();
      console.log(newTime,day);
      if (newTime > day) {
        // console.log('我是新的一天,我要弹窗')
        showOption.value = true;
      } else {
        showOption.value = false;
      }
    }
  }
  // 取消商会意见
  function cancelOption() {
    showOption.value = false;
  }
  // // 确认不再提示
  function ok() {
    var newTime = new Date().getDate();
    setcookieTimeFun(`urgencyCookie${route.query.id}`, newTime, 1)
    showOption.value = false;
  }
  
  getList();
  </script>
  <style lang="scss" scoped>
  .container {
    margin: 0px auto;
    height: 100%;
    width: 1200px;
    overflow-x: hidden;
    overflow-y: auto;
  
    .worrning {
      width: 340px;
      height: 110px;
      color: #3d4a5d;
      font-size: 18px;
      line-height: 26px;
      background: #f5f9fe;
      margin: 30px auto 10px;
      padding: 15px;
    }
  
    .header {
      padding: 10px 0px;
  
      .title {
        font-size: 18px;
        font-weight: bold;
      }
  
      div {
        height: 60px;
        line-height: 60px;
        margin-top: 10px;
  
        &.icon {
          padding: 0 20px;
          background: #f5f9fe;
        }
      }
    }
  }
  </style>
  